/** 裁剪图片,裁剪成16:9的图片即给width传16,height传9 */
const cutPicture = (rawFile, width, height) => {
  let _URL = window.URL || window.webkitURL;
  let image = new Image();
  image.src = _URL.createObjectURL(rawFile);
  image.onload = function () {
    const that = this;
    // 默认按比例压缩
    let w = that.width;
    let h = that.height;

    if (w / h > width / height) {
      w = (width * h) / height;
    } else if (w / h < width / height) {
      h = (height * w) / width;
    } else {
      return rawFile;
    }

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    // 创建属性节点
    const anw = document.createAttribute("width");
    anw.nodeValue = w;
    const anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);

    const data = canvas.toDataURL("image/jpeg", 0.7);
    const newFile = convertBase64UrlToBlob(data);
    return newFile;
  };
};

const convertBase64UrlToBlob = (urlData) => {
  const bytes = window.atob(urlData.split(",")[1]);
  // 去掉url的头，并转换为byte
  // 处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], { type: "image/png" });
};

/** 判断是否为手机号*/
const checkPhone = (rule, value, callback) => {
  let isPhone = /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/;
  setTimeout(() => {
    if (value && !isPhone.test(value)) {
      callback(new Error("请输入正确的手机号"));
    } else {
      callback();
    }
  }, 1000);
};

export { cutPicture, convertBase64UrlToBlob, checkPhone };
